<template>
  <div class="project-detail-page">
    <!-- 顶部标题 -->
    <Header />
    <div class="back-page">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <el-link type="primary" @click="goBack" icon="DArrowLeft">返回</el-link>
        <span v-if="type != 'apply'">首页 / 我的控制台 / 我参与的项目 / 查看项目详情</span>
        <span v-else>首页 / 公告-综合评分类 / 公告详情 / 上传资料报名</span>
      </div>

      <!-- 页面内容 -->
      <div class="content">
        <h2>项目报名</h2>

        <!-- 项目信息 -->
        <section class="section">
          <div style="display: flex; align-items: center">
            <div style="width: 6px; background: rgb(24, 144, 255); height: 20px; margin-right: 5px"></div>
            <h3>项目信息</h3>
          </div>
          <el-form :model="projectInfo" label-width="120px">
            <el-row :gutter="20" class="gradient-box" style="margin-left: 0; padding-top: 20px">
              <el-col :span="12">
                <el-form-item label="项目编号 :">
                  <span>{{ projectInfo.oaCode }}</span>
                </el-form-item>
                <el-form-item label="项目名称 :">
                  <span>{{ projectInfo.name }}</span>
                </el-form-item>
                <el-form-item label="发布时间 :">
                  <span>{{ projectInfo.createTime }}</span>
                </el-form-item>
                <el-form-item label="征集截止日期 :">
                  <span>{{ projectInfo.applyEndTime }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目状态 :">
                  <span>{{ getDictValue(projectStatusOptions, projectInfo.status) }}</span>
                </el-form-item>
                <el-form-item label="评审日期 :">
                  <span>{{ projectInfo.auditTime }}</span>
                </el-form-item>
                <el-form-item label="征集起始日期 :">
                  <span>{{ projectInfo.applyStartTime }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </section>

        <!-- 上传报名资料 -->
        <section class="section">
          <div style="display: flex; align-items: center">
            <div style="width: 6px; background: rgb(24, 144, 255); height: 20px; margin-right: 5px"></div>
            <h3>上传报名资料</h3>
          </div>
          <el-form :model="participantInfo" ref="formRef" label-width="120px" :rules="rules">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="报告供应商名称">
                  <el-input v-model="participantInfo.name" disabled />
                </el-form-item>
                <el-form-item label="报名时间" v-if="type !== 'apply'">
                  <el-input v-model="participantInfo.reportTime" disabled />
                </el-form-item>
                <el-form-item label="公司电子邮箱">
                  <el-input v-model="participantInfo.supplierEmail" disabled />
                </el-form-item>
                <el-form-item label="报名人姓名" prop="supplierName">
                  <el-input v-model="participantInfo.supplierName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商编号">
                  <el-input v-model="participantInfo.supplierCode" disabled />
                </el-form-item>
                <el-form-item label="报名人电话" prop="supplierPhone">
                  <el-input v-model="participantInfo.supplierPhone" />
                </el-form-item>
                <el-form-item label="参选人是否为制造商或下属子公司">
                  <el-radio-group v-model="participantInfo.isFactory">
                    <el-radio label="是" value="1" />
                    <el-radio label="否" value="0" />
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </section>

        <!-- 文件上传部分 -->
        <section class="section" v-if="projectValueList.length">
          <div style="display: flex; align-items: center">
            <div style="width: 6px; background: rgb(24, 144, 255); height: 20px; margin-right: 5px"></div>
            <h3>供应商资质审查文件</h3>
          </div>
          <div v-for="item in projectValueList" :key="item.id" class="upload-item">
            <p class="file-description">{{ item.textValue }}</p>

            <!-- 文件上传框 -->
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :on-preview="(file) => handlePreview(file, item.id)"
              :on-remove="(file, fileList) => handleRemove(file, fileList, item.id)"
              :before-remove="(file, fileList) => beforeRemove(file, fileList, item.id)"
              :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, item.id)"
              :on-change="(file, fileList) => handleChange(file, fileList, item.id)"
              :limit="1"
              :file-list="fileListUpload[item.id] || []"
              :auto-upload="false"
              :accept="'.pdf'"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                资质文件要求：<br />
                - 必须为清晰，完整的原件扫描件或数码照<br />
                - 仅支持PDF格式，且不超过1M<br />
                - 必须在有效期内且年检章齐全
              </div>
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            </el-upload>

            <!-- 文件显示部分 -->
            <div class="file-display" v-if="type != 'apply'">
              <!-- <el-image :src="fileListUpload[item.id][0].url || fileListUpload[item.id][0].preview" fit="contain" class="file-preview" /> -->
              <div class="file-actions">
                <el-link type="primary" @click="downloadFile(fileListUpload[item.id][0])">下载</el-link>
                <el-link type="default" @click="previewFile(fileListUpload[item.id][0])">预览</el-link>
                <el-link type="danger" @click="deleteFile(fileListUpload[item.id][0], item.id)">删除</el-link>
              </div>
            </div>
          </div>
        </section>
        <section class="section" v-if="projectInfo.type !== 'project_relative_price'">
          <div style="display: flex; align-items: center">
            <div style="width: 6px; background: rgb(24, 144, 255); height: 20px; margin-right: 5px"></div>
            <h3>供应商参选文件</h3>
          </div>
          <div class="upload-item">
            <p class="file-description">供应商参选文件</p>
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :before-remove="beforeRemoveZip"
              :on-success="(response, file, fileList) => handleCandidateUploadChange(file, fileList)"
              :on-change="(file, fileList) => handleCandidateUploadChange(file, fileList)"
              :limit="1"
              :file-list="fileListUploadCandidate"
              :auto-upload="false"
              :accept="'.rar,.zip'"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                参选文件要求：<br />
                - 必须上传加密的文件压缩包（限.rar或.zip格式），请自行保存好密码<br />
                - 如上传无加密的文件压缩包，将视为供应商放弃参选！
              </div>
            </el-upload>

            <div class="file-display" v-if="type != 'apply'">
              <div class="file-actions" v-for="file in fileListUploadCandidate" :key="file.uid">
                <el-link type="primary" @click="downloadFile(file)">下载</el-link>
                <el-link type="danger" @click="deleteCandidateFile(file)">删除</el-link>
              </div>
            </div>
          </div>
        </section>
        <section class="section" v-else>
          <div style="display: flex; align-items: center">
            <div style="width: 6px; background: rgb(24, 144, 255); height: 20px; margin-right: 5px"></div>
            <h3>供应商报价文件</h3>
          </div>
          <div class="upload-item">
            <p class="file-description">供应商报价文件</p>
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :on-preview="(file) => handlePreview(file, item.id)"
              :before-remove="beforeRemoveZip"
              :on-success="(response, file, fileList) => handleCandidateUploadChange(file, fileList)"
              :on-change="(file, fileList) => handleCandidateUploadChange(file, fileList)"
              :limit="1"
              :file-list="fileListUploadCandidate"
              :auto-upload="false"
              :accept="'.pdf'"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                报价文件上传须知：<br />
                1、请上传已盖公司章的PDF格式报价文件<br />
                2、评审日后如贵司中选，项目联系人将收<br />
                - 到评审人员的电话通知，请保持电话畅通。<br />
                3、如贵司未中选，评审日后将不会另行通知，敬请留意！
              </div>
            </el-upload>

            <div class="file-display" v-if="type != 'apply'">
              <div class="file-actions" v-for="file in fileListUploadCandidate" :key="file.uid">
                <el-link type="primary" @click="downloadFile(file)">下载</el-link>
                <el-link type="danger" @click="deleteCandidateFile(file)">删除</el-link>
              </div>
            </div>
          </div>
        </section>

        <div style="display: flex; justify-content: center; align-items: center">
          <el-button type="primary" @click="submitForm" style="margin-top: 20px; width: 300px; height: 42px">报名</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { getNoticeInfo } from "@/api/projectNotice";
import { uploadProjectFile, applySupplier } from "@/api/apply";
import { useDataStore } from "@/store/index.js"; // 引入 Pinia Store
import Header from "../../components/Header.vue";

const dataStore = useDataStore(); // 使用 Pinia Store
const projectStatusOptions = computed(() => dataStore.project_status);

const route = useRoute();
const router = useRouter();
//项目id
const projectId = computed(() => route.query.id);
//状态
const type = computed(() => route.query.type);
//供应商信息
const userInfo = computed(() => JSON.parse(localStorage.getItem("supplierInfo")));
//项目信息
const projectInfo = ref({});
//报名资料
const participantInfo = ref({
  name: "",
  applyTime: "",
  supplierCode: "",
  supplierName: "",
  supplierPhone: "",
  supplierEmail: "",
  isFactory: "1",
});
const formRef = ref(null);
const rules = {
  supplierPhone: [
    { required: true, message: "报名人电话不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: ["blur", "change"],
    },
  ],
  supplierName: [{ required: true, message: "报名人不能为空", trigger: "blur" }],
};
//文件列表
const projectValueList = ref([]);

//上传的文件列表
const fileListUpload = ref({});
//单独管理参选文件
const fileListUploadCandidate = ref([]);
const generatePreviewUrl = (path) => {
  // 确保路径正确，适配后端服务地址
  const baseUrl = import.meta.env.VITE_APP_BASE_API;
  return `${baseUrl}${path}`;
};
const handlePreview = (file, id) => {
  const url = generatePreviewUrl(file.url);
  window.open(url, "_blank");
};
const goBack = () => {
  router.go(-1);
};
const handleRemove = (file, fileList, id) => {
  console.log(`Remove file in ID ${id}:`, file, fileList);
};
const beforeRemoveZip = (file) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`);
};
const handleCandidateUploadChange = async (file, fileList) => {
  if (file.size > 1024 * 1024 * 5) {
    ElMessage.error("文件大小不能超过5MB");
    fileListUploadCandidate.value = fileList.filter((f) => f.uid !== file.uid);
    return;
  }
  // 创建一个新的文件对象，避免直接修改原始文件名
  const newFile = new File([file.raw], participantInfo.value.name + "-" + file.raw.name, { type: file.raw.type });

  const formData = new FormData();
  formData.append("file", newFile);
  formData.append("projectCode", projectInfo.value.oaCode);
  formData.append("projectId", projectId.value);

  try {
    const response = await uploadProjectFile(formData);
    if (response && response.code === 200) {
      fileListUploadCandidate.value.push({
        name: participantInfo.value.name + "-" + file.name,
        url: response.fileName,
        uid: file.uid,
      });
      ElMessage.success(`文件 ${file.name} 上传成功`);
    } else {
      ElMessage.error(`文件上传失败：${response.message || "未知错误"}`);
    }
  } catch (error) {
    ElMessage.error(`文件上传失败：${error.message || "网络错误"}`);
  }
};

const deleteCandidateFile = (file) => {
  const index = fileListUploadCandidate.value.findIndex((f) => f.uid === file.uid);
  if (index !== -1) {
    fileListUploadCandidate.value.splice(index, 1);
  }
};
const beforeRemove = (file, fileList, id) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`);
};
const handleSuccess = (response, file, fileList, id) => {
  if (!fileListUpload.value[id]) {
    fileListUpload.value[id] = [];
  }
  fileListUpload.value[id].push(file);
  ElMessage.success(`文件 ${file.name} 上传成功`);
};

const handleChange = async (file, fileList, id) => {
  // 检查文件大小限制
  if (file.size > 1024 * 1024 * 5) {
    ElMessage.error("文件大小不能超过5MB");
    fileListUpload.value[id] = fileListUpload.value[id]?.filter((f) => f.uid !== file.uid);
    return;
  }

  // 获取 projectCode
  const projectCode = projectInfo.value.oaCode; // 从项目信息中获取 projectCode

  // 创建一个新的文件对象，避免直接修改原始文件名
  const newFile = new File([file.raw], participantInfo.value.name + "-" + file.raw.name, { type: file.raw.type });

  // 创建 FormData
  const formData = new FormData();
  formData.append("file", newFile);
  formData.append("projectCode", projectCode);
  formData.append("projectId", projectId.value);

  try {
    // 调用上传接口
    const response = await uploadProjectFile(formData);

    if (response && response.code == 200) {
      // 确保 `fileListUpload` 对应的 ID 已初始化
      if (!fileListUpload.value[id]) {
        fileListUpload.value[id] = [];
      }

      // 将上传返回的文件路径存储到 fileListUpload
      fileListUpload.value[id].push({
        name: participantInfo.value.name + "-" + file.name,
        url: response.fileName, // 假设返回的路径字段为 filePath
        uid: file.uid,
      });

      ElMessage.success(`文件 ${file.name} 上传成功`);
    } else {
      ElMessage.error(`文件上传失败：${response.message || "未知错误"}`);
    }
  } catch (error) {
    ElMessage.error(`文件上传失败：${error.message || "网络错误"}`);
  }
};

const deleteFile = (file, id) => {
  const index = fileListUpload.value[id]?.findIndex((f) => f.uid === file.uid);
  if (index !== -1) {
    fileListUpload.value[id].splice(index, 1);
  }
  console.log(`Delete file in ID ${id}:`, file);
};

const downloadFile = (file) => {
  console.log("下载文件：", file.name);
};

const previewFile = (file) => {
  console.log("预览文件：", file.name);
};
//处理报名所需要的数据
const transformData = (participantInfo, fileListUpload, projectValueList) => {
  const valueList = projectValueList.map((item) => {
    const { id, projectId, useObject, type, textValue: title } = item; // 解构需要的字段

    // 查找文件列表中与当前 id 匹配的文件
    const files = fileListUpload[id] || [];

    // 将文件的 url 拼接成以逗号分隔的字符串
    const pushValue = files.map((file) => file.url).join(",");

    return {
      supplierId: participantInfo.supplierId,
      projectId,
      valueId: id,
      useObject,
      type,
      title,
      pushValue,
    };
  });
  valueList.push({
    supplierId: participantInfo.supplierId,
    projectId: projectId.value,
    title: projectInfo.value.type == "project_relative_price" ? "供应商报价文件" : "供应商参选文件",
    type: "pdf_apply_file",
    pushValue: fileListUploadCandidate.value.length ? fileListUploadCandidate.value[0].url : "",
    useObject: "use_supplier",
    valueId: "0",
  });
  // 返回合并后的对象
  return {
    ...participantInfo,
    valueList,
  };
};
const getDictValue = (list, value) => {
  return list.find((item) => item.dictValue == value)?.dictLabel;
};
//报名
const submitForm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const result = transformData(participantInfo.value, fileListUpload.value, projectValueList.value);

      // 验证方法
      const validateData = (data) => {
        for (const item of data.valueList) {
          if (!item.pushValue || !item.pushValue.trim()) {
            ElMessage.error(`"${item.title}" 的值不能为空`);
            return false;
          }
        }
        return true;
      };

      // 调用验证
      if (!validateData(result)) {
        return; // 验证不通过直接返回
      }

      const res = await applySupplier(result);
      if (res.code == 200) {
        ElMessage.success("报名成功");
        router.push("/index");
      }
    } else {
      ElMessage.error(`请检查表格数据`);
    }
  });
};

onMounted(() => {
  getNoticeInfo(projectId.value).then((res) => {
    if (res.code == 200) {
      projectInfo.value = res.data;
      projectValueList.value = [];
      projectValueList.value = res.data.projectValueList.filter((item) => item.textValue && item.type != "pdf_attachment_notice");
    }
  });
  if (type.value == "apply") {
    const { enterprise, code, email, id } = userInfo.value;
    participantInfo.value.name = enterprise;
    participantInfo.value.supplierCode = code;
    participantInfo.value.supplierEmail = email;
    participantInfo.value.projectId = projectId.value;
    participantInfo.value.supplierId = id;
  }
});
</script>

<style scoped>
.back-page {
  min-height: calc(100vh - 56px);
  background: url("../../assets/f87147698f07020d4fea348f49da0166.png") no-repeat center center;
  background-size: cover;
}
.header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ddd;
}
.header span {
  font-size: 18px;
  font-weight: bold;
  margin-left: 16px;
}
.breadcrumb {
  color: #888;
  font-size: 14px;
  padding: 16px;
  padding-bottom: 0;
  padding-left: 0;
  width: 80%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  span {
    margin-left: 20px;
  }
}
.content {
  padding: 16px;
  padding-top: 0;
  padding-bottom: 50px;
  width: 80%;
  margin: 0 auto;
}
.section {
  margin-bottom: 24px;
  padding: 0 20px;
  max-width: 1000px;
  margin: 0 auto 24px;
}
.file-description {
  font-size: 14px;
  color: #555;
  margin-bottom: 10px;
}

.file-display {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
}

.file-preview {
  width: 100%;
  max-width: 100px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.file-actions {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}
.file-group {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}
.file-item {
  width: 120px;
  text-align: center;
}
.file-item .file-actions {
  margin-top: 8px;
}
</style>
